<?php
/**
 * @orm tablename newsletter_lists
 */
class NewsletterList extends DomArObject {
	
	/**
	 * @orm char(60)
	 */
	public $name;
	/**
	 * @orm plugin DomArDateTime(now)
	 */
	public $createdTime;
	/**
	 * @orm longtext
	 */
	public $comment;
	/**
	 * @orm owns many NewsletterEmail inverse list 
	 */
	public $emails;
	/**
	 * @orm has parent NewsletterSend inverse list
	 */
	public $sends;
	
	public function importFromCsv( $csvString ) {
		
		//$query = 'INSERT INTO '.NewsLetterEmail::getDbTable().' (email,name,list,active) VALUES ';
		$added = 0;
		$errors = 0;
		$existing = 0;
		$problematicEmails = array();
		foreach( explode("\n",$csvString) as $row ) {
			$row = trim($row);
			
			if( $row == '' ) {
				continue;
			}
			
			$row = explode(',',$row);
			foreach( $row as &$element ) {
				$element = trim($element);
				if( $element[0] == '"' && $element[strlen($element)-1] == '"') {
					$element = substr($element,1,-1);
				}
			}

			$model = new NewsletterEmail();
			$model->list = $this;
			$model->email = $row[0];
			$model->name = $row[1];
			$model->active = true;
			if( $model->validated() == false ) {
				$this->emails->unload( $model );
				$errors++;
				$problematicEmails[] = $model->getValidationMessages(',').": ".$row[2].", ".$row[0];
			} else {
				try {
					if( $model->save() ) {
						$added++;
					} else {
						throw new RuntimeException('Failed saving email: '.$row[2].", ".$row[0]);
					}
				} catch( Exception $e ) {
					// duplicate key
					if( $e->getCode() == 1062 ) {
						$existing++;
					} else {
						throw $e;
					}
				}
			}
		}
		
		return array(
			'added' => $added,
			'errors' => $errors,
			'existing' => $existing,
			'problematicEmails' => $problematicEmails,
		);
	}
	
}
?>